package com.zegome.game.gomestory.main.scene.menu;

import org.json.JSONArray;
import org.json.JSONObject;

import android.util.Log;
import aurelienribon.tweenengine.BaseTween;
import aurelienribon.tweenengine.Tween;
import aurelienribon.tweenengine.TweenCallback;
import aurelienribon.tweenengine.equations.Cubic;
import aurelienribon.tweenengine.equations.Sine;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.scenes.scene2d.ui.ImageButton;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener.ChangeEvent;
import com.facebook.Session;
import com.zegome.facebook.IFacebookBridge;
import com.zegome.facebook.IFacebookEventListener;
import com.zegome.facebook.IFacebookProcessorListener;
import com.zegome.game.gomestory.main.A;
import com.zegome.game.gomestory.main.D;
import com.zegome.game.gomestory.main.helper.DailyGift;
import com.zegome.game.gomestory.main.helper.GameAdvertise;
import com.zegome.game.gomestory.main.helper.Gift;
import com.zegome.game.gomestory.main.helper.IMActionBoolean;
import com.zegome.game.gomestory.main.helper.IWMAction;
import com.zegome.game.gomestory.main.libs.PNG;
import com.zegome.game.gomestory.main.scene.BaseGameScreen;
import com.zegome.game.main.AndroidGameController;
import com.zegome.game.util.helper.WidgetAccessor;
import com.zegome.game.util.helper.input.IMAction;
import com.zegome.payment.appota.IAppotaPaymentProcessorListener;

public class MenuScreen extends BaseGameScreen{

	private Image bg,logo, nameGame;
	private ImageButton play, online, special,fb;
	private ImageButton fbShare;
	
	public MenuScreen(AndroidGameController controller, String name, final IFacebookBridge bridge) {
		super(controller, name,bridge);		
		setConfig(true, true, true,true);		
	}

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub		
		super.onCreate();		
		ctr.a.loadedCommond2();
		ctr.a.loadedMenu();
		ctr.a.loadedMusic1();	
		ctr.a.loadedMusic2();
		ctr.a.loadedGame();
		ctr.a.loadedSplash();
		ctr.autoRunText.setBitmapFont(ctr.g.mFont);
		ctr.inputTextAndroid = mController.getInputText();
	}
	
	public MenuScreen(AndroidGameController controller, String name, SpriteBatch spriteBatch) {
		super(controller,name, spriteBatch);
		setConfig(true, true, true,true);
	}

	@Override
	public void onManagedUpdate(float pDeltaTime) {
		// TODO Auto-generated method stub		
		//Log.e("PDELTATIME", pDeltaTime+"");				
		if(ctr.d.isHelpMenuFinish == false && ctr.a.isHasDialog() == false){
			ctr.stageHelper.createHelpMenu(stage, tweenManager);
			ctr.d.isHelpMenuFinish = true;
			ctr.controller.getActivity().getPreference().saveValue("HelpMenu", true);
		}
		if(ctr.d.isLoginedFB == true){
			if(fb!=null && fb.isVisible())
				fb.setVisible(false);		
			if(fbShare!=null && !fbShare.isVisible())
				fbShare.setVisible(true);
		}
		
		if((ctr.d.isNetworkAvaiable&&ctr.d.isCheckVersion && ctr.d.isVersionLatest == false&&ctr.d.isShowDialogUpdateVersion == false)||(!ctr.d.isNetworkAvaiable&&ctr.d.isShowDialogUpdateVersion == false&& ctr.d.isVersionLatest == false)){
			if(!ctr.a.isHasDialog()){
				ctr.d.isShowDialogUpdateVersion = true;
				ctr.stageHelper.createDialog(stage, tweenManager, ctr.lang.getUpdateGame(ctr.d.messageUpdate),
						1, 
						new ChangeListener() {
							
							@Override
							public void changed(ChangeEvent arg0, Actor arg1) {
								// TODO Auto-generated method stub
								ctr.androidHelper.openGooglePlay(ctr.d.packageName);
								postRunnable(new Runnable() {
									
									@Override
									public void run() {
										// TODO Auto-generated method stub
										Gdx.app.exit();
									}
								});								
							}
						}, null);
			}
		}
				
		update(pDeltaTime);
		
		if(ctr.d.isLogined && ctr.d.isNetworkAvaiable){
			if(ctr.d.passScreen[0] && ctr.d.passScreen[1] && ctr.d.passScreen[2] && ctr.d.passScreen[3]){
				if(!ctr.a.isHasDialog()){
					if(ctr.d.isShowOneTask){
						for(int j =0;j<4; j++){
							if(ctr.d.passTask[j] == false){
								ctr.stageHelper.createDialogTask(this,stage, tweenManager, j);
								ctr.d.isShowOneTask = false;
								break;
							}
						}						
					}
				}
			}
		}
		
		super.onManagedUpdate(pDeltaTime);
	}
	@Override
	public void resume() {
		// TODO Auto-generated method stub		
		fb.setVisible(!ctr.d.isLoginedFB);
		fbShare.setVisible(ctr.d.isLoginedFB);
		
		super.resume();
				
	}
	public void show() {
		ctr.a.soundOnOff();
		state = 0;
		ctr.a.isHasDialog.removeAllElements();
		ctr.d.backLis.removeAllElements();
		
		tweenManager.killAll();
		stage.clear();
		createUi();		
		super.show();
		ctr.a.bgSong.play();
		
		if(ctr.d.isNetworkAvaiable == false){
			ctr.androidHelper.showToast(ctr.lang.turnOnNetworkGift);
		}
		fb.setVisible(!ctr.d.isLoginedFB);
		fbShare.setVisible(ctr.d.isLoginedFB);
		if(ctr.d.passScreen[D.MENU] == false){
			ctr.d.passScreen[D.MENU] = true;
			ctr.d.saveAccount();
		}
	}

	public void createUi() {
		if (bg == null) {
			bg = ctr.stageHelper.createImage(ctr.a.bgMenu, 0, 0);
			bg.setSize((800), (480));		
		}		
		if (logo == null) {
			logo = ctr.stageHelper.createImage(ctr.a.logoRegion, 0, 0);
			logo.setSize((302), (278));
			logo.setPosition((60), (60));
			logo.setOrigin(151, 139);
		}

		if (play == null) {
			play = ctr.stageHelper.createImageButton(ctr.g.mSkin, ctr.a.playNorRegion,
					ctr.a.playPressRegion, null, 0, 0);
			play.addListener(new ChangeListener() {
				@Override
				public void changed(ChangeEvent event, Actor actor) {					
					if(ctr.a.isHasDialog() == true)
						return;
					if(state!=1){
						return;
					}
					ctr.a.yesSound.play(ctr.a.vls);		
					
					if((ctr.a.isLoadedChapter)){												
					}
					else{						
						if(ctr.a.isLoadedVS){
							ctr.a.unloadVS();							
						}
						if(ctr.a.isLoadedDraw)
							ctr.a.unloadDraw();
						ctr.a.loadChapter();
						ctr.a.loadLevel();
						getController().finishLoading();
						ctr.a.loadedChapter();
						//ctr.a.loadedLevel();
					}
									
					fadeOut(new TweenCallback() {
						
						@Override
						public void onEvent(int arg0, BaseTween<?> arg1) {
							// TODO Auto-generated method stub
							ctr.a.bgSong.pause();
							ctr.a.clearMenu();
							ctr.a.loadedChapter();
							clear();
							mController.setScreen(mController
									.getScreen("ChapterScreen"));													
						}
					});
				}
			});
		}

		if (online == null) {
			online = ctr.stageHelper.createImageButton(ctr.g.mSkin, ctr.a.onlineNorRegion,
					ctr.a.onlinePressRegion, null, 0, 0);
			online.addListener(new ChangeListener() {
				@Override
				public void changed(ChangeEvent event, Actor actor) {
					if(ctr.a.isHasDialog() == true)
						return;
					if(state!=1)
						return;					
					
					ctr.a.yesSound.play(ctr.a.vls);					
					
					final IMAction action = new IMAction() {
						
						@Override
						public void action() {
							// TODO Auto-generated method stub
							if((ctr.a.isLoadedVS)){												
							}
							else{						
								if(ctr.a.isLoadedChapter){
									ctr.a.unloadChapter();
									ctr.a.unloadLevel();
								}
								if(ctr.a.isLoadedDraw)
									ctr.a.unloadDraw();
								ctr.a.loadVS();
								getController().finishLoading();
								ctr.a.loadedVS();
							}
							fadeOut(new TweenCallback() {
								
								@Override
								public void onEvent(int arg0, BaseTween<?> arg1) {
									// TODO Auto-generated method stub
									ctr.a.bgSong.pause();
									ctr.a.clearMenu();
									clear();
									ctr.a.loadedVS();
									mController.setScreen(mController
											.getScreen("VSScreen"));
								}
							});
						}
					};
				
					
					if(ctr.d.isNetworkAvaiable == false){
						ctr.stageHelper.createDialog(stage, tweenManager, ctr.lang.turnOnNetWorkToPlayVS, 1, null, null);
						return;
					}
					else {
						if(!ctr.d.isLogined() && ctr.d.isHasAccount){		
							setWaitAction(new  IMActionBoolean() {
						
						@Override
						public boolean isFinish() {
							// TODO Auto-generated method stub
							return ctr.d.isLogined();
						}
						
						@Override
						public void end() {
							// TODO Auto-generated method stub
							action.action();
							ctr.stageHelper.dimissDialogLoading();
						}
						
						@Override
						public void begin() {
							// TODO Auto-generated method stub
							ctr.stageHelper.createDialogLoading(stage, tweenManager);
						}
					});
						}
						else if(ctr.d.isHasAccount == false){
							//action.action();
							final IWMAction loginSuccess = new IWMAction() {					
								@Override
								public void action(String result) {						
									try{
									JSONObject jsObj = new JSONObject(result);
									// TODO Auto-generated method stub
									if (result == null) {
										ctr.d.isSendingLogin = false;
									} else {																				
										 if(jsObj.getString("code").equals("1")){
											 
											 ctr.d.name = ctr.d.namePre;
											 ctr.d.email = ctr.d.emailPre;
											 ctr.d.pass = ctr.d.passPre;	
											 
											 JSONObject content = jsObj.getJSONObject("content");
											 								 								 
											 JSONArray messages = content.getJSONArray("message");
											 
											 JSONArray gifts = content.getJSONArray("gift");

											 JSONArray advertise = content.getJSONArray("advertise");
											 
											 try{
											 JSONArray giftsDaily = content.getJSONArray("daily_gift");										
											 for(int i=0; i<giftsDaily.length(); i++){
													 JSONObject ele = giftsDaily.getJSONObject(i);
													 ctr.d.dailyGifts.add(new DailyGift(ele.getInt("zegome_gold"), ele.getString("message")));
												 }
											 }
											 catch(Exception ex){}
											 for(int i=0; i<messages.length(); i++){
												 JSONObject ele = messages.getJSONObject(i);
												 ctr.autoRunText.addNotify(0,ctr.d.isVietnamese?ele.getString("message_content"):ele.getString("message_eng"),null,null);
											 }
											 
											 for(int i=0; i<advertise.length(); i++){
												 JSONObject ele = advertise.getJSONObject(i);
												 //ctr.a.notify.add(ele.getString("gift_id") +"-"+ele.getString("user_send")+"-"+ele.getString("zegome_gold")+"-"+ele.getString("coupon")+"-"+ele.getString("message"));
												 ctr.d.gameAdvertiseLoad.add(i,new GameAdvertise(i,ele.getString("icon"), ele.getString("link"), ctr.d.isVietnamese?ele.getString("message_vn"):ele.getString("message_eng")));
											 }
											 
											 for(int i=0; i<gifts.length(); i++){
												 JSONObject ele = gifts.getJSONObject(i);
												 //ctr.a.notify.add(ele.getString("gift_id") +"-"+ele.getString("user_send")+"-"+ele.getString("zegome_gold")+"-"+ele.getString("coupon")+"-"+ele.getString("message"));
												 ctr.d.gifts.add(new Gift(ele.getInt("gift_id"), ele.getString("user_send"), ele.getInt("zegome_gold"), ele.getString("coupon"), ele.getString("message")));
											 }
											 								
											 								 
											 ctr.d.moneyOnline = content.getInt("user_gome");
											 ctr.d.level = content.getInt("level");
											 ctr.d.total_win = content.getInt("total_win");
											 ctr.d.total_lose = content.getInt("total_lose");
											 ctr.d.achievement = content.getString("achievement");
											 ctr.d.exp = content.getInt("experiment");
											 ctr.d.star = content.getInt("star");
											 ctr.d.isHasAccount = true;
											 ctr.d.saveAccount();						
											 ctr.d.isLogined = true;
											 ctr.d.isSendingLogin = false;								 								 
											 ctr.stageHelper.dimissDialogLoading();
										 }
										 else {
											 
											 logout();											 
											 ctr.stageHelper.createDialogErrorLogin(stage, tweenManager, ctr.lang.error+": "+jsObj.getString("content"), 2, null);											 
											 ctr.d.isSendingLogin = false;
										 }
										 
									}
								}
									catch(Exception ex){
										ctr.androidHelper.log(ex.getMessage());
									}
								}
							};				
							ctr.stageHelper.createDialogLogin(stage, tweenManager, "", "", loginSuccess, null, null, null);
						}
						else{
							action.action();
						}
					}
				}
			});
		}
		
		if (special == null) {
			special = ctr.stageHelper.createImageButton(ctr.g.mSkin, ctr.a.specialNorRegion,
					ctr.a.specialPressRegion, null, 0, 0);
			special.addListener(new ChangeListener() {
				@Override
				public void changed(ChangeEvent event, Actor actor) {					
					if(ctr.a.isHasDialog() == true)
						return;
					if(state!=1)
						return;
					ctr.a.yesSound.play(ctr.a.vls);			
					
					final IMAction action = new IMAction() {
						
						@Override
						public void action() {
							// TODO Auto-generated method stub
							if((ctr.a.isLoadedDraw)){												
							}
							else{						
								if(ctr.a.isLoadedChapter){
									ctr.a.unloadChapter();
									ctr.a.unloadLevel();
								}
								if(ctr.a.isLoadedVS)
									ctr.a.unloadVS();
								ctr.a.loadDraw();
								getController().finishLoading();
								ctr.a.loadedDraw();
							}
												
							fadeOut(new TweenCallback() {
								
								@Override
								public void onEvent(int arg0, BaseTween<?> arg1) {
									// TODO Auto-generated method stub
									ctr.a.bgSong.pause();
									clear();
									ctr.a.clearMenu();
									ctr.a.loadedDraw();
									mController.setScreen(mController
											.getScreen("DrawScreen"));
								}
							});
						}
					};
				
								
					
					if(false){		
						ctr.stageHelper.createDialog(stage, tweenManager, ctr.lang.turnOnNetWorkToPlayVS, 1, null, null);
						return;
					}
					else{						
						if(false){		
							setWaitAction(new  IMActionBoolean() {
						
						@Override
						public boolean isFinish() {
							// TODO Auto-generated method stub
							return ctr.d.isLogined();
						}
						
						@Override
						public void end() {
							// TODO Auto-generated method stub
							action.action();
							ctr.stageHelper.dimissDialogLoading();
						}
						
						@Override
						public void begin() {
							// TODO Auto-generated method stub
							ctr.stageHelper.createDialogLoading(stage, tweenManager);
						}
					});
						}
						else if(false){
							
							final IWMAction loginSuccess = new IWMAction() {					
								@Override
								public void action(String result) {						
									try{
									JSONObject jsObj = new JSONObject(result);
									// TODO Auto-generated method stub
									if (result == null) {
										ctr.d.isSendingLogin = false;
									} else {																				
										 if(jsObj.getString("code").equals("1")){
											 
											 ctr.d.name = ctr.d.namePre;
											 ctr.d.email = ctr.d.emailPre;
											 ctr.d.pass = ctr.d.passPre;	
											 
											 JSONObject content = jsObj.getJSONObject("content");
											 								 								 
											 JSONArray messages = content.getJSONArray("message");
											 
											 JSONArray gifts = content.getJSONArray("gift");

											 try{
											 JSONArray giftsDaily = content.getJSONArray("daily_gift");										
											 for(int i=0; i<giftsDaily.length(); i++){
													 JSONObject ele = giftsDaily.getJSONObject(i);
													 ctr.d.dailyGifts.add(new DailyGift(ele.getInt("zegome_gold"), ele.getString("message")));
												 }
											 }
											 catch(Exception ex){}
											 for(int i=0; i<messages.length(); i++){
												 JSONObject ele = messages.getJSONObject(i);
												 ctr.autoRunText.addNotify(0,ele.getString("message_content"),null,null);
											 }
											 
											 for(int i=0; i<gifts.length(); i++){
												 JSONObject ele = gifts.getJSONObject(i);
												 //ctr.a.notify.add(ele.getString("gift_id") +"-"+ele.getString("user_send")+"-"+ele.getString("zegome_gold")+"-"+ele.getString("coupon")+"-"+ele.getString("message"));
												 ctr.d.gifts.add(new Gift(ele.getInt("gift_id"), ele.getString("user_send"), ele.getInt("zegome_gold"), ele.getString("coupon"), ele.getString("message")));
											 }
											 								
											 								 
											 ctr.d.moneyOnline = content.getInt("user_gome");
											 ctr.d.level = content.getInt("level");
											 ctr.d.total_win = content.getInt("total_win");
											 ctr.d.total_lose = content.getInt("total_lose");
											 ctr.d.achievement = content.getString("achievement");
											 ctr.d.exp = content.getInt("experiment");
											 ctr.d.star = content.getInt("star");											 
											 ctr.d.saveAccount();																							 								 
											 ctr.stageHelper.dimissDialogLoading();
											 ctr.d.isLogined = true;
											 ctr.d.isSendingLogin = false;	
											 ctr.d.isHasAccount = true;
										 }
										 else {
											 ctr.stageHelper.createDialog(stage, tweenManager, ctr.lang.error+": "+jsObj.getString("content"), 1, null, null);
											 ctr.d.isSendingLogin = false;
										 }
										 
									}
								}
									catch(Exception ex){
										ctr.androidHelper.log(ex.getMessage());
									}
								}
							};				
							
							ctr.stageHelper.createDialogLogin(stage, tweenManager, "", "", loginSuccess, null, null, null);
							
							//action.action();
					}
						else{
							action.action();
						}
					}
				}
			});
		}
		
		if (fb == null) {
			fb = ctr.stageHelper.createImageButton(ctr.g.mSkin, ctr.a.facebook,
					null, null, 0, 0);
			fb.addListener(new ChangeListener() {
				
				@Override
				public void changed(ChangeEvent arg0, Actor arg1) {
					// TODO Auto-generated method stub
					if(ctr.a.isHasDialog() == true||ctr.a.isFbAction)
						return;
					if(!ctr.d.isNetworkAvaiable){
						ctr.androidHelper.showToast(ctr.lang.turnOnNetworkForTask);
						return;
					}
					ctr.a.isFbAction = true;
					afterAction = null;
					mAction = IFacebookProcessorListener.LOGIN;
					mFBBridge.onLogin(MenuScreen.this);					
				}
			});
		}
		
		if (fbShare == null) {
			fbShare = ctr.stageHelper.createImageButton(ctr.g.mSkin, ctr.a.fbShareMenu,
					null, null, 0, 0);
			fbShare.addListener(new ChangeListener() {
				
				@Override
				public void changed(ChangeEvent arg0, Actor arg1) {
					if(ctr.a.isHasDialog() == true||ctr.a.isFbAction)
						return;
					if(!ctr.d.isNetworkAvaiable){
						ctr.androidHelper.showToast(ctr.lang.turnOnNetworkForTask);
						return;
					}
					// TODO Auto-generated method stub
					ctr.stageHelper.createDialogShareFB(MenuScreen.this, stage, tweenManager);
				}
			});
		}
			
		stage.addActor(bg);
		addIconGomeSmallStage();
		stage.addActor(play);
		stage.addActor(online);
		stage.addActor(special);		
		stage.addActor(fb);
		stage.addActor(fbShare);
		Table avatar = ctr.stageHelper.createAvatar(this,stage, tweenManager, (0), (480-99), 1f);
		stage.addActor(avatar);
		
		online.setPosition((473), (480));
		play.setPosition((487), (480));
		special.setPosition((487), (480));
		fb.setPosition((492), (480));
		fbShare.setPosition((492), (480));
				
		nameGame = ctr.stageHelper.createImage(ctr.a.nameGame, 100, 290);
						
		stage.addActor(logo);
		stage.addActor(nameGame);
		
		Tween.to(logo, WidgetAccessor.SCALE_XY, 2f)
		.ease(Cubic.INOUT)
		.target(1.07f, 1f)
		.repeatYoyo(-1, 0f)
		.start(tweenManager);
		
		Tween.to(logo, WidgetAccessor.POS_XY, 2f)
		.ease(Cubic.INOUT)
		.targetRelative(0f, 4f)
		.repeatYoyo(-1, 0f)
		.start(tweenManager);
		
		
		Tween.to(online, WidgetAccessor.POS_XY, 0.8f).target((473), (480 - 230)).ease(Sine.OUT).start(tweenManager);
		Tween.to(play, WidgetAccessor.POS_XY, 0.8f).target((487), (480-146)).ease(Sine.OUT).start(tweenManager);
		Tween.to(special, WidgetAccessor.POS_XY, 0.8f).target((487), (480-313)).ease(Sine.OUT).start(tweenManager);
		Tween.to(fb, WidgetAccessor.POS_XY, 0.8f).target((492), (480-400)).ease(Sine.OUT).start(tweenManager);
		Tween.to(fbShare, WidgetAccessor.POS_XY, 0.8f).target((492), (480-400)).ease(Sine.OUT).start(tweenManager);
	}
		
		
	public void backKeyProcess(){
		if(ctr.a.isHasDialog() == true)
			return;
		if(ctr.showMobileCore(null)){
			return;
		}
		//postRunnable(new Runnable() {
			
		//	@Override
		//	public void run() {				
				// TODO Auto-generated method stub
				ctr.stageHelper.createDialogExit(stage, tweenManager, ctr.lang.exitGameConfirm, 2,
						new ChangeListener() {							
							@Override
							public void changed(ChangeEvent arg0, Actor arg1) {
								// TODO Auto-generated method stub
//								MobileCore.showOfferWall(ctr.androidHelper.activity, new CallbackResponse() {
//									
//									@Override
//									public void onConfirmation(TYPE arg0) {
								
									
								// TODO Auto-generated method stub
								postRunnable(new Runnable() {
									
									@Override
									public void run() {
										// TODO Auto-generated method stub
										Gdx.app.exit();
									}
								});
									//}
								//});	
							}
						}, null);
		//	}
		//});
	}
	
		
	public void clear(){
		super.clear();
		bg = null;
		logo = null;
		nameGame = null;
		play = null; online = null; special = null; fb = null;		
	}
}
